import 'dart:math';

import 'package:airbnb_clone/components/dialog/msg_dialog.dart';
import 'package:airbnb_clone/internal/cache/app_cache.dart';
import 'package:airbnb_clone/internal/http/dao/login_dao.dart';

import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:go_router/go_router.dart';

import '../../models/response.dart';

class LoginPageScreen extends StatefulWidget {
  const LoginPageScreen({super.key});

  @override
  State<LoginPageScreen> createState() => _LoginPageScreenState();
}

class _LoginPageScreenState extends State<LoginPageScreen> {
  final Random _random = Random();
  final GlobalKey _formKey = GlobalKey<FormState>();
  late int _randomNumber;
  bool _passWordMd = true;
  String passWord = "";
  String account = "";
  final Map<int, String> _randomBackgroundMap = {
    1: "assets/images/bg1.jpg",
    2: "assets/images/bg2.jpg",
    3: "assets/images/bg3.jpg",
    4: "assets/images/bg4.jpg",
    5: "assets/images/bg5.jpg",
    6: "assets/images/bg6.jpg",
    7: "assets/images/bg7.jpg"
  };
  @override
  void initState() {
    super.initState();
    setState(() {
      _randomNumber = _random.nextInt(7) + 1;
    });
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Material(
      child: Scaffold(
        body: SizedBox(
          height: size.height,
          child: Stack(
            children: [
              SizedBox(
                  height: size.height * 0.5, child: randomBackground(context)),
              Positioned.fill(
                  top: size.height * 0.4,
                  child: SingleChildScrollView(
                    child: SizedBox(
                        height: size.height * 0.6, child: loginForm(context)),
                  ))
            ],
          ),
        ),
      ),
    );
  }

  // 背景图片
  Widget randomBackground(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(),
      child: ClipRRect(
          borderRadius: BorderRadius.circular(8),
          child: Image.asset(
            _randomBackgroundMap[_randomNumber]!,
            fit: BoxFit.cover,
          )),
    ).animate(delay: const Duration(milliseconds: 300)).fadeIn();
  }

  // 表单
  Widget loginForm(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(40),
      decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(30))),
      child: Form(
        key: _formKey,
        autovalidateMode: AutovalidateMode.onUserInteraction,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            // 账号字段
            TextFormField(
              onSaved: (newValue) => account = newValue!,
              validator: (value) {
                if (value!.isEmpty) {
                  return "Account Cant null";
                }
              },
              decoration: const InputDecoration(
                prefixIcon: Icon(Icons.person),
                labelText: "Account",
                helperText: "Account",
                hintText: "Plase Input User Account",
              ),
            ),
            // 密码字段
            TextFormField(
                // controller: _pwController,
                obscureText: _passWordMd,
                validator: (value) {
                  if (value!.isEmpty) {
                    return "Password Cant null";
                  }
                },
                onSaved: (newValue) => passWord = newValue!,
                decoration: InputDecoration(
                  helperText: "Password",
                  labelText: "PassWord",
                  hintText: "Plase Input User PassWord",
                  prefixIcon: const Icon(Icons.lock),
                  suffixIcon: IconButton(
                    icon: Icon(
                      Icons.remove_red_eye,
                      color: _passWordMd ? Colors.grey : Colors.blueAccent,
                    ),
                    onPressed: () {
                      setState(() {
                        _passWordMd = !_passWordMd;
                      });
                    },
                  ),
                )),
            // 登录按钮
            ElevatedButton(
              onPressed: () {
                if ((_formKey.currentState as FormState).validate()) {
                  (_formKey.currentState as FormState).save();

                  login(context);
                }
              },
              // style: ElevatedButton.styleFrom(
              //     backgroundColor: Colors.blue.withOpacity(0.8),
              //     side: BorderSide(color: Colors.blue, width: 2),
              //     shape: RoundedRectangleBorder(
              //         borderRadius: BorderRadius.circular(10))),
              child: const Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [Icon(Icons.login_sharp), Text("登录")],
              ),
            ),
            // 注册跳转
            GestureDetector(
              onTap: () {
                context.pop();
                context.pushNamed("register");
              },
              child: Center(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Text(
                      "no account?\t",
                      style: TextStyle(fontSize: 20),
                    ),
                    Text(
                      "register now",
                      style: TextStyle(
                          fontSize: 20, color: Theme.of(context).primaryColor),
                    )
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Future<void> login(BuildContext context) async {
    // print("$account,$passWord");
    // AppCache.setToken("token");

    TiebaResponse response = await LoginDao.login(account, passWord);
    if (response.code == 200) {
      // print(response.result['token']);
      AppCache.setToken(response.result['token']);
      // ignore: use_build_context_synchronously
      context.pop();
    } else {
      // ignore: use_build_context_synchronously
      MsgDialog.msgDialog(context, response.msg);
    }

    // AppCache.cleanToken();
  }
}
